package edu.tgc.log;

import java.util.Date;

import org.abyss.utils.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import edu.tgc.entity.log.LogEntry;
import edu.tgc.repository.LogEntryRespository;

@Component
public class LogEntryFailedListener implements ApplicationListener<AbstractAuthenticationFailureEvent> {

    @Autowired
    protected LogEntryRespository logEntryRespository;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        String username = (String) event.getAuthentication().getPrincipal();
        String ip = ((WebAuthenticationDetails) event.getAuthentication().getDetails()).getRemoteAddress();
        Date createTime = new Date(event.getTimestamp());
        this.logEntryRespository.save(LogEntry.faild(username, ip, createTime, event.getException().getMessage(), event.getException().getClass().getName()));
        if (this.logger.isInfoEnabled()) {
            this.logger.info(DateTimeUtils.toLong(createTime) + ":" + username + "(" + ip + ")登陆失败，原因：" + event.getException().getMessage());
        }
    }

}
